console.log("SwiftShadow Downloader content script loaded.");

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === "download_current_page") {
        console.log("Content script received download request for: " + request.url);
        // Here you could potentially extract more information from the page
        // before sending it to the background script.
        // For now, just forward it.
        chrome.runtime.sendMessage({action: "download_current_page", url: request.url});
    }
});

function injectDownloadButton(mediaElement) {
    if (mediaElement.dataset.swiftshadowDownloadButtonInjected) {
        return; // Already injected
    }

    const downloadButton = document.createElement('button');
    downloadButton.textContent = 'Download (SwiftShadow)';
    downloadButton.style.cssText = `
    margin-left: 10px;
    padding: 5px 10px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
  `;

    downloadButton.addEventListener('click', () => {
        const mediaUrl = mediaElement.src;
        if (mediaUrl) {
            console.log('Sending download request for:', mediaUrl);
            chrome.runtime.sendMessage({action: 'download_resource', url: mediaUrl});
        }
    });

    // Insert the button after the media element
    mediaElement.parentNode.insertBefore(downloadButton, mediaElement.nextSibling);
    mediaElement.dataset.swiftshadowDownloadButtonInjected = 'true';
}

function processMediaElements() {
    document.querySelectorAll('video, audio').forEach(injectDownloadButton);
}

// Initial scan for existing media elements
processMediaElements();

// Observe DOM for dynamically added media elements
const observer = new MutationObserver(mutations => {
    mutations.forEach(mutation => {
        if (mutation.addedNodes) {
            mutation.addedNodes.forEach(node => {
                if (node.nodeType === 1) { // Element node
                    if (node.matches('video, audio')) {
                        injectDownloadButton(node);
                    } else if (node.querySelector('video, audio')) {
                        node.querySelectorAll('video, audio').forEach(injectDownloadButton);
                    }
                }
            });
        }
    });
});

observer.observe(document.body, {childList: true, subtree: true});